package com.goldplusgold.tradedelay.app.trade.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.goldplusgold.support.lib.utils.InputMethodUtil;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.support.lib.widget.recyclerview.adapter.RecyclerViewBaseAdapter;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.network.lib.http.protobuf.Market;
import com.goldplusgold.tradedelay.app.trade.activity.ProfitAndLossActivity;
import com.goldplusgold.tradedelay.app.trade.dialog.DeleteDialog;
import com.goldplusgold.tradedelay.app.trade.pojo.TriggeredRecord;
import com.goldplusgold.support.lib.utils.StringConvertNumber;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/26.
 */

public class ProfitAndLossAdapter extends RecyclerViewBaseAdapter<TriggeredRecord> {

    public Context context;

    public final static int ITEM_PROFIT_NORMAL = 101;
    public final static int ITEM_LOSS_NORMAL = 103;
    public final static int ITEM_PROFIT_NEW = 105;
    public final static int ITEM_LOSS_NEW = 106;

    public static final int ITEM_BOTH_EMPTY = 108;
    public static final int ITEM_LOSS_EMPTY = 109;
    public static final int ITEM_PROFIT_EMPTY = 110;

    private String bearbullType;
    private Market.QuoteDyna quoteDyna;
    private String prodCode;
    private int lots;

    public ProfitAndLossAdapter(Context ctx, String bearbullType, String prodCode, int lots) {
        super(ctx);
        this.bearbullType = bearbullType;
        this.lots = lots;
        this.prodCode = prodCode;
    }

    public void setQuoteDyna(Market.QuoteDyna quoteDyna) {
        this.quoteDyna = quoteDyna;
    }

    @Override
    public RecyclerViewBaseAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ViewHolder viewHolder = null;
        View itemView;
        switch (viewType) {
            case ITEM_PROFIT_NORMAL:
                itemView = getLayoutInflater().inflate(R.layout.item_profit_normal, parent, false);
                itemView.setTag("profitNormal");
                viewHolder = new NormalItemViewHolder(itemView);
                itemView.setTag(viewHolder);
                break;
            case ITEM_PROFIT_NEW:
                itemView = getLayoutInflater().inflate(R.layout.newly_added_profit, parent, false);
                itemView.setTag("profitNew");
                viewHolder = new NewlyAddedItemViewHolder(itemView);
                itemView.setTag(viewHolder);
                break;
            case ITEM_LOSS_NORMAL:
                itemView = getLayoutInflater().inflate(R.layout.item_loss_normal, parent, false);
                itemView.setTag("lossNormal");
                viewHolder = new NormalItemViewHolder(itemView);
                itemView.setTag(viewHolder);
                break;
            case ITEM_LOSS_NEW:
                itemView = getLayoutInflater().inflate(R.layout.newly_added_loss, parent, false);
                itemView.setTag("lossNew");
                viewHolder = new NewlyAddedItemViewHolder(itemView);
                itemView.setTag(viewHolder);
                break;
            case ITEM_PROFIT_EMPTY:
                itemView = getLayoutInflater().inflate(R.layout.item_profit_no_list, parent, false);
                viewHolder = new EmptyItemViewHolder(itemView);
                itemView.setTag(viewHolder);
                break;
            case ITEM_LOSS_EMPTY:
                itemView = getLayoutInflater().inflate(R.layout.item_loss_no_list, parent, false);
                viewHolder = new EmptyItemViewHolder(itemView);
                itemView.setTag(viewHolder);
                break;
            case ITEM_BOTH_EMPTY:
                itemView = getLayoutInflater().inflate(R.layout.item_no_list, parent, false);
                viewHolder = new NewlyAddedItemViewHolder(itemView);
                itemView.setTag(viewHolder);
                break;
            default:
                break;
        }
        return viewHolder;

    }


    @Override
    public int getItemViewType(int position) {
        TriggeredRecord triggeredRecord = getItem(position);
        if (triggeredRecord != null) {
            return triggeredRecord.getViewType();
        }
        return ITEM_BOTH_EMPTY;
    }

    public TriggeredRecord getProfitEmptyItem() {
        TriggeredRecord triggeredRecord = new TriggeredRecord();
        triggeredRecord.setViewType(ProfitAndLossAdapter.ITEM_PROFIT_EMPTY);
        triggeredRecord.setSltpType("TP");
        return triggeredRecord;
    }

    public TriggeredRecord getLossEmptyItem() {
        TriggeredRecord triggeredRecord = new TriggeredRecord();
        triggeredRecord.setViewType(ProfitAndLossAdapter.ITEM_LOSS_EMPTY);
        triggeredRecord.setSltpType("SL");
        return triggeredRecord;
    }


    public class NormalItemViewHolder extends RecyclerViewBaseAdapter.ViewHolder {
        RelativeLayout headProfitLayout;
        RelativeLayout mEditLayout;
        RelativeLayout mDeleteLayout;
        String mType;
        private TextView mPrice;
        private TextView mHand;
        private TextView mFloatPrice;

        public NormalItemViewHolder(View contentView) {
            super(contentView);
            mType = (String) contentView.getTag();
        }

        @Override
        protected void createViewHolderAction(View contentView) {
            headProfitLayout = (RelativeLayout) contentView.findViewById(R.id.rl_profit_settings);
            mEditLayout = (RelativeLayout) contentView.findViewById(R.id.id_normal_edit_layout);
            mDeleteLayout = (RelativeLayout) contentView.findViewById(R.id.id_normal_delete_layout);

            mPrice = (TextView) contentView.findViewById(R.id.tv_normal_price);
            mHand = (TextView) contentView.findViewById(R.id.tv_normal_hand);
            mFloatPrice = (TextView) contentView.findViewById(R.id.tv_normal_float_price);
        }

        @Override
        public void bindViewHolderAction(final int position) {
            final TriggeredRecord triggeredRecord = getItem(position);
            if (triggeredRecord != null) {
                mHand.setText("手数：" + triggeredRecord.getLots() + "手");
                mFloatPrice.setText("滑点价：" + triggeredRecord.getFloatPrice() + "元");
            }

            setHeadDisplay(triggeredRecord, position, headProfitLayout);
            if (!TextUtils.isEmpty(mType)) {
                switch (mType) {
                    case "profitNormal":
                        mPrice.setText("止盈价：" + triggeredRecord.getSltpPrice());
                        mEditLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (hasNoSaveItem()) {
                                    Activity activity = (Activity) getContext();
                                    if (activity instanceof ProfitAndLossActivity) {
                                        ((ProfitAndLossActivity) activity).displaySaveDialog((ProfitAndLossActivity) activity);
                                    }
                                    return;
                                }

                                triggeredRecord.setViewType(ITEM_PROFIT_NEW);
                                notifyDataSetChanged();
                            }
                        });

                        break;
                    case "lossNormal":
                        mPrice.setText("止损价：" + triggeredRecord.getSltpPrice());
                        mEditLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (hasNoSaveItem()) {
                                    Activity activity = (Activity) getContext();
                                    if (activity instanceof ProfitAndLossActivity) {
                                        ((ProfitAndLossActivity) activity).displaySaveDialog((ProfitAndLossActivity) activity);
                                    }
                                    return;
                                }

                                triggeredRecord.setViewType(ITEM_LOSS_NEW);
                                notifyDataSetChanged();
                            }
                        });
                        break;
                }
            }

            mDeleteLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (hasNoSaveItem()) {
                        Activity activity = (Activity) getContext();
                        if (activity instanceof ProfitAndLossActivity) {
                            ((ProfitAndLossActivity) activity).displaySaveDialog((ProfitAndLossActivity) activity);
                        }
                        return;
                    }
                    deleteAction(position);
                }

            });
            mFloatPrice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String message = "";
                    if (!TextUtils.isEmpty(bearbullType)) {
                        switch (bearbullType) {
                            case "BEAR":
                                message = "对于空头：触发时，系统自动发出平仓委托，委托价为最新价加上滑点价，但不保证成交";
                                break;
                            case "BULL":
                                message = "对于多头，触发时，系统自动发出平仓委托，委托价为最新价减去滑点价，但不保证成交";
                                break;
                        }
                        showPopupWindowByNoEditState(message, mFloatPrice);
                    }
                }
            });

        }
    }


    private void deleteAction(int position) {
        DeleteDialog deleteDialog = DeleteDialog.newInstance(position);
        Activity activity = (Activity) getContext();
        if (activity instanceof ProfitAndLossActivity) {
            FragmentManager fm = ((ProfitAndLossActivity) activity).getSupportFragmentManager();
            deleteDialog.show(fm, null);
        }
    }

    private void addAndUpdateAction(TriggeredRecord triggeredRecord, int position) {

        String id = triggeredRecord.getId();
        if (!TextUtils.isEmpty(id)) {
            updateItem(triggeredRecord);
        } else {
            addItem(triggeredRecord, position);
        }
    }

    private void addItem(TriggeredRecord triggeredRecord, int position) {
        Activity activity = (Activity) getContext();
        if (activity instanceof ProfitAndLossActivity) {
            //String prodCode, String bearbullType, String sltpType, String sltpPrice, String floatPrice, String lots
            ((ProfitAndLossActivity) activity).new AddProfitAndLossItemAsync(
                    triggeredRecord, position).execute(AsyncTask.TYPE_NET);
        }
    }

    private void updateItem(TriggeredRecord triggeredRecord) {
        Activity activity = (Activity) getContext();
        if (activity instanceof ProfitAndLossActivity) {
            //String id, String prodCode, String bearbullType, String sltpType,
            //String sltpPrice, String floatPrice, String lots
            ((ProfitAndLossActivity) activity).new UpdateProfitAndLossItemAsync(
                    triggeredRecord.getId(),
                    triggeredRecord.getProdCode(),
                    triggeredRecord.getBearbullType(),
                    triggeredRecord.getSltpType(),
                    triggeredRecord.getSltpPrice(),
                    triggeredRecord.getFloatPrice(),
                    triggeredRecord.getLots()).execute(AsyncTask.TYPE_NET);
        }
    }


    private boolean validateItem(TriggeredRecord triggeredRecord) {

        if (triggeredRecord == null || quoteDyna == null) {
            return false;
        }

        String message = "";
        String sltpPriceStr = triggeredRecord.getSltpPrice();
        String sltpType = triggeredRecord.getSltpType();
        String lotsStr = triggeredRecord.getLots();

        if (TextUtils.isEmpty(sltpPriceStr) && !TextUtils.isEmpty(sltpType)) {
            switch (sltpType) {
                case "TP":
                    message = "请输入止盈价";
                    break;
                case "SL":
                    message = "请输入止损价";
                    break;
            }

            showPrompt(message);
            return false;
        }

        if (TextUtils.isEmpty(lotsStr)) {
            message = "请输入手数";
            showPrompt(message);
            return false;
        }

        double sltpPrice = StringConvertNumber.parseDouble(sltpPriceStr);
        double lastPrice = StringConvertNumber.parseDouble(quoteDyna.getLastPrice());
        double highestPrice = StringConvertNumber.parseDouble(quoteDyna.getHighestPrice());
        double lowestPrice = StringConvertNumber.parseDouble(quoteDyna.getLowestPrice());


        if (!TextUtils.isEmpty(sltpType) && !TextUtils.isEmpty(bearbullType)) {
            switch (bearbullType) {
                case "BEAR":
                    switch (sltpType) {
                        case "TP":
                            if (sltpPrice > lastPrice || sltpPrice < lowestPrice) {
                                message = "止盈价需在最新价与跌停价之间，请修改";
                            }
                            break;
                        case "SL":
                            if (sltpPrice < lastPrice || sltpPrice > highestPrice) {
                                message = "止损价需在最新价和涨停价之间，请修改";
                            }
                            break;
                    }
                    break;
                case "BULL":
                    switch (sltpType) {
                        case "TP":
                            if (sltpPrice < lastPrice || sltpPrice > highestPrice) {
                                message = "止盈价需在最新价和涨停价之间，请修改";
                            }
                            break;
                        case "SL":
                            if (sltpPrice > lastPrice || sltpPrice < lowestPrice) {
                                message = "止损价需在最新价与跌停价之间，请修改";
                            }
                            break;
                    }
                    break;
            }

        }

        if (!TextUtils.isEmpty(message)) {
            showPrompt(message);
            return false;
        }
        return true;
    }


    private void showPrompt(String message) {
        Activity activity = (Activity) getContext();
        if (activity instanceof ProfitAndLossActivity) {
            ((ProfitAndLossActivity) activity).operationQueryStatePrompt(message);
        }
    }


    private boolean validateLotsItem(int lotsItem, TriggeredRecord triggeredRecord) {
        String message = "";
        if (triggeredRecord == null) {
            return false;
        }
        String sltyType = triggeredRecord.getSltpType();
        switch (sltyType) {
            case "TP":
                int enableProfitLots = getEnableProfitLots(triggeredRecord);
                if (lotsItem > enableProfitLots) {
                    message = "最多可设置" + enableProfitLots + "手";
                }
                break;
            case "SL":
                int enableLossLots = getEnableLossLots(triggeredRecord);
                if (lotsItem > enableLossLots) {
                    message = "最多可设置" + enableLossLots + "手";
                }
                break;
        }

        Activity activity = (Activity) getContext();
        if (activity instanceof ProfitAndLossActivity) {
            if (!TextUtils.isEmpty(message)) {
                ((ProfitAndLossActivity) activity).operationStatePrompt(message);
                return false;
            }
        }
        return true;
    }


    public class EmptyItemViewHolder extends RecyclerViewBaseAdapter.ViewHolder {

        public EmptyItemViewHolder(View contentView) {
            super(contentView);
        }

        @Override
        protected void createViewHolderAction(View contentView) {

        }

        @Override
        public void bindViewHolderAction(int position) {

        }
    }

    public class NewlyAddedItemViewHolder extends RecyclerViewBaseAdapter.ViewHolder {
        //用来判断当前的ViewHolder是止盈还是止损条目
        RelativeLayout headProfitLayout;
        String mType;
        RelativeLayout mCancelLayout;
        RelativeLayout mSaveLayout;
        TextView mQuestion;
        EditText mHands;
        EditText mPrice;
        EditText mFloat;
        private TextView mTextFloatPrice;

        public NewlyAddedItemViewHolder(View contentView) {
            super(contentView);
            mType = (String) contentView.getTag();
        }


        private void setFloatInput() {
            if (!TextUtils.isEmpty(prodCode)) {
                switch (prodCode) {
                    case "Ag(T+D)":
                        mFloat.setInputType(InputType.TYPE_CLASS_NUMBER);
                        break;
                    case "Au(T+D)":
                    case "mAu(T+D)":
                        mFloat.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                        break;
                }
            }
        }

        @Override
        protected void createViewHolderAction(View contentView) {
            headProfitLayout = (RelativeLayout) contentView.findViewById(R.id.rl_profit_settings);
            mCancelLayout = (RelativeLayout) contentView.findViewById(R.id.id_newly_added_cancel);
            mSaveLayout = (RelativeLayout) contentView.findViewById(R.id.id_newly_added_save);
            mQuestion = (TextView) contentView.findViewById(R.id.tv_added_entrust);
            mFloat = (EditText) contentView.findViewById(R.id.et_added_float_price);
            setFloatInput();
            mPrice = (EditText) contentView.findViewById(R.id.et_added_price);
            mHands = (EditText) contentView.findViewById(R.id.et_added_hands);
            mTextFloatPrice = (TextView) contentView.findViewById(R.id.tv_added_text_float_price);
        }

        @Override
        public void bindViewHolderAction(final int position) {
            final TriggeredRecord triggeredRecord = getItem(position);
            setHeadDisplay(triggeredRecord, position, headProfitLayout);
            if (triggeredRecord != null && !TextUtils.isEmpty(triggeredRecord.getId())) {
                mPrice.setText(triggeredRecord.getSltpPrice());
                mHands.setText(triggeredRecord.getLots());
                mFloat.setText(triggeredRecord.getFloatPrice());
            } else {
                mPrice.getEditableText().clear();
                mHands.getEditableText().clear();
                mFloat.setText("0");
            }

            final CustomFloatTextWatcher floatTextWatcher = new CustomFloatTextWatcher(triggeredRecord);

            final CustomTextWatcher textWatcher = new CustomTextWatcher(triggeredRecord, mHands);
            if (!TextUtils.isEmpty(mType)) {
                switch (mType) {
                    case "profitNew":
                        switch (bearbullType) {
                            case "BEAR":
                                mPrice.setHint("最新价与跌停间");
                                mTextFloatPrice.setText("滑点价：触发后，以最新价加");
                                break;
                            case "BULL":
                                mPrice.setHint("最新价与涨停间");
                                mTextFloatPrice.setText("滑点价：触发后，以最新价减");
                                break;
                        }
                        mSaveLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mFloat.removeTextChangedListener(floatTextWatcher);
                                mHands.removeTextChangedListener(textWatcher);

                                saveClickAction(triggeredRecord, "TP", position);
                            }
                        });
                        mHands.setHint("可用" + getEnableProfitLots(triggeredRecord) + "手");
                        break;
                    case "lossNew":
                        switch (bearbullType) {
                            case "BEAR":
                                mPrice.setHint("最新价与涨停间");
                                mTextFloatPrice.setText("滑点价：触发后，以最新价加");
                                break;
                            case "BULL":
                                mPrice.setHint("最新价与跌停间");
                                mTextFloatPrice.setText("滑点价：触发后，以最新价减");
                                break;
                        }

                        mSaveLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mFloat.removeTextChangedListener(floatTextWatcher);
                                mHands.removeTextChangedListener(textWatcher);

                                saveClickAction(triggeredRecord, "SL", position);
                            }
                        });
                        mHands.setHint("可用" + getEnableLossLots(triggeredRecord) + "手");
                        break;
                }
            }

            mCancelLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    mFloat.removeTextChangedListener(floatTextWatcher);
                    mHands.removeTextChangedListener(textWatcher);
                    if (triggeredRecord != null) {
                        String id = triggeredRecord.getId();
                        if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(mType)) {
                            switch (mType) {
                                case "profitNew":
                                    triggeredRecord.setViewType(ITEM_PROFIT_NORMAL);
                                    notifyDataSetChanged();

                                    break;
                                case "lossNew":
                                    triggeredRecord.setViewType(ITEM_LOSS_NORMAL);
                                    notifyDataSetChanged();
                                    break;
                            }
                            return;
                        }

                    }

                    getArrayList().remove(position);
                    addEmptyItem();
                    notifyDataSetChanged();
                }
            });


            mQuestion.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String message = "";
                    if (!TextUtils.isEmpty(bearbullType)) {
                        switch (bearbullType) {
                            case "BEAR":
                                message = "对于空头：触发时，系统自动发出平仓委托，但不保证成交";
                                break;
                            case "BULL":
                                message = "对于多头，触发时，系统自动发出平仓委托，但不保证成交";
                                break;
                        }
                        showPopupWindow(message, mQuestion);
                    }
                }
            });

            mHands.addTextChangedListener(textWatcher);
            mFloat.addTextChangedListener(floatTextWatcher);

        }


        private void saveClickAction(TriggeredRecord triggeredRecord, String sltpType, int position) {
            if (TextUtils.isEmpty(sltpType)) {
                return;
            }
            triggeredRecord.setSltpPrice(mPrice.getText().toString());
            triggeredRecord.setLots(mHands.getText().toString());
            triggeredRecord.setFloatPrice(mFloat.getText().toString());
            triggeredRecord.setSltpType(sltpType);

            if (validateItem(triggeredRecord)) {
                switch (sltpType) {
                    case "TP":
                        triggeredRecord.setViewType(ITEM_PROFIT_NORMAL);
                        break;
                    case "SL":
                        triggeredRecord.setViewType(ITEM_LOSS_NORMAL);
                        break;
                }


                addAndUpdateAction(triggeredRecord, position);
                if (InputMethodUtil.isInputMethodShowing(getContext())) {
                    InputMethodUtil.hideInputMethod(getContext());
                }
            }
        }
    }


    class CustomTextWatcher implements TextWatcher {

        private TriggeredRecord triggeredRecord;
        private EditText mEditText;

        public CustomTextWatcher(TriggeredRecord triggeredRecord, EditText editText) {
            this.triggeredRecord = triggeredRecord;
            this.mEditText = editText;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() > 0) {
                String value = s.toString();
                if (TextUtils.equals("0", value)) {
                    s.clear();
                }
                int usedLots = StringConvertNumber.parseInt(value);
                if (!validateLotsItem(usedLots, triggeredRecord)) {
                    if (triggeredRecord != null) {
                        String sltpType = triggeredRecord.getSltpType();
                        if (TextUtils.isEmpty(sltpType)) {
                            return;
                        }
                        switch (sltpType) {
                            case "TP":
                                String profitHands = String.valueOf(getEnableProfitLots(triggeredRecord));
                                mEditText.setText(profitHands);
                                break;
                            case "SL":
                                String lossHands = String.valueOf(getEnableLossLots(triggeredRecord));
                                mEditText.setText(lossHands);
                                break;
                        }

                        mEditText.setSelection(mEditText.getText().length());
                    }
                }
            }
        }
    }


    class CustomFloatTextWatcher implements TextWatcher {

        private TriggeredRecord triggeredRecord;

        public CustomFloatTextWatcher(TriggeredRecord triggeredRecord) {
            this.triggeredRecord = triggeredRecord;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() > 0) {
                String value = s.toString();
                triggeredRecord.setFloatPrice(value);
            }
        }
    }

    public void addLossItem() {

        if (getSizeEmptyLoss() > 0) {
            int index = getSizeStopProfits();
            getArrayList().remove(index);
        }

        TriggeredRecord triggeredRecord = new TriggeredRecord();
        triggeredRecord.setViewType(ITEM_LOSS_NEW);
        triggeredRecord.setSltpType("SL");
        int size = getItemCount();
        setSortList(triggeredRecord, size);
    }

    public void addProfitsItem() {
        if (getSizeEmptyStopProfits() > 0) {
            getArrayList().remove(0);
        }

        TriggeredRecord triggeredRecord = new TriggeredRecord();
        triggeredRecord.setViewType(ITEM_PROFIT_NEW);
        triggeredRecord.setSltpType("TP");
        int size = getSizeStopProfits();
        setSortList(triggeredRecord, size);
    }

    public void addEmptyItem() {
        if (getSizeStopProfits() == 0 && getSizeEmptyStopProfits() == 0) {
            getArrayList().add(0, getProfitEmptyItem());
        }

        if (getSizeStopLosses() == 0 && getSizeEmptyLoss() == 0) {
            int index = getSizeStopProfits();
            getArrayList().add(index, getLossEmptyItem());
        }
    }

    private void setHeadDisplay(TriggeredRecord triggeredRecord, int position, RelativeLayout headProfitLayout) {
        if (triggeredRecord != null) {
            String sltpType = triggeredRecord.getSltpType();
            if (TextUtils.isEmpty(sltpType)) {
                return;
            }
            switch (sltpType) {
                case "TP":
                    if (position == 0) {
                        headProfitLayout.setVisibility(View.VISIBLE);
                    } else {
                        headProfitLayout.setVisibility(View.GONE);
                    }
                    break;
                case "SL":
                    if (getSizeStopProfits() == position) {
                        headProfitLayout.setVisibility(View.VISIBLE);
                    } else {
                        headProfitLayout.setVisibility(View.GONE);
                    }
                    break;
            }

        }

    }

    public static final int NO_EDIT_STATE = 0x10;
    public static final int EDIT_STATE = 0x09;

    public void showPopupWindow(String message, View view) {
        createPopupWindow(message, view, EDIT_STATE);
    }

    public void showPopupWindowByNoEditState(String message, View view) {
        createPopupWindow(message, view, NO_EDIT_STATE);
    }

    private void createPopupWindow(String message, View view, int type) {
        View contentView = getLayoutInflater().inflate(R.layout.jiaoketanchuang, null);
        int width = getContext().getResources().getDimensionPixelOffset(R.dimen.popup_window_width);
        int height = getContext().getResources().getDimensionPixelOffset(R.dimen.popup_window_height);

        int xoff = getContext().getResources().getDimensionPixelOffset(R.dimen.popup_window_xoff);
        int yoff = getContext().getResources().getDimensionPixelOffset(R.dimen.popup_window_yoff);

        PopupWindow window = new PopupWindow(contentView, width, height);

        window.setOutsideTouchable(true);
        window.setFocusable(true);
        window.setBackgroundDrawable(new ColorDrawable(0x00000000));
        if (contentView != null) {
            TextView textView = (TextView) contentView.findViewById(R.id.id_text_view_tip);
            textView.setText(message);
        }
        window.update(view, width, height);
        if (window.isShowing()) {
            window.dismiss();
        } else {
            switch (type) {
                case NO_EDIT_STATE:
                    window.showAsDropDown(view, -(view.getWidth() + xoff), 0);
                    break;
                case EDIT_STATE:
                    window.showAsDropDown(view, -(view.getWidth() + xoff), 0);
                    break;
            }
        }
    }


    private void setSortList(TriggeredRecord triggeredRecord, int position) {
        ArrayList<TriggeredRecord> list = getArrayList();
        if (list == null) {
            list = new ArrayList<>();
        }
        list.add(position, triggeredRecord);
        notifyDataSetChanged();
    }


    public int getSizeStopProfits() {
        return getSizeItem("TP");
    }


    public int getSizeStopLosses() {
        return getSizeItem("SL");
    }


    private int getSizeItem(String sltpType) {
        ArrayList<TriggeredRecord> triggeredRecords = getArrayList();
        List<TriggeredRecord> records = new ArrayList<>();
        if (triggeredRecords == null || triggeredRecords.isEmpty()) {
            return 0;
        }
        for (TriggeredRecord triggeredRecord : triggeredRecords) {
            if (TextUtils.equals(sltpType, triggeredRecord.getSltpType())
                    && (triggeredRecord.getViewType() != ITEM_PROFIT_EMPTY
                    || triggeredRecord.getViewType() != ITEM_LOSS_EMPTY)) {
                records.add(triggeredRecord);
            }
        }
        return records.size();
    }

    public int getSizeEmptyStopProfits() {
        return getSizeEmptyItem("TP");
    }

    public int getSizeEmptyLoss() {
        return getSizeEmptyItem("SL");
    }

    private int getSizeEmptyItem(String sltpType) {
        ArrayList<TriggeredRecord> triggeredRecords = getArrayList();
        List<TriggeredRecord> records = new ArrayList<>();
        if (triggeredRecords == null || triggeredRecords.isEmpty()) {
            return 0;
        }
        for (TriggeredRecord triggeredRecord : triggeredRecords) {
            if (TextUtils.equals(sltpType, triggeredRecord.getSltpType())
                    && (triggeredRecord.getViewType() == ITEM_PROFIT_EMPTY
                    || triggeredRecord.getViewType() == ITEM_LOSS_EMPTY)) {
                records.add(triggeredRecord);
            }
        }
        return records.size();
    }


    public int getEnableProfitLots(TriggeredRecord value) {
        return getLots(value, "TP");
    }

    public int getEnableLossLots(TriggeredRecord value) {
        return getLots(value, "SL");
    }

    public int getLots(TriggeredRecord value, String sltpTypeValue) {
        int enableLots = lots;

        ArrayList<TriggeredRecord> triggeredRecords = getArrayList();
        if (triggeredRecords == null || triggeredRecords.isEmpty()) {
            return enableLots;
        }
        for (TriggeredRecord triggeredRecord : triggeredRecords) {
            if (value != null && TextUtils.equals(value.getId(), triggeredRecord.getId())) {
                continue;
            }
            String sltpType = triggeredRecord.getSltpType();
            if (TextUtils.isEmpty(sltpType) || !TextUtils.equals(sltpType, sltpTypeValue)) {
                continue;
            }
            enableLots = enableLots - StringConvertNumber.parseInt(triggeredRecord.getLots());
        }
        //stopProfits
        return enableLots;

    }


    public int getEnableLossLots() {
        return getEnableLossLots(null);
    }

    public int getEnableProfitLots() {
        return getEnableProfitLots(null);
    }

    public boolean hasNoSaveItem() {
        ArrayList<TriggeredRecord> triggeredRecords = getArrayList();
        if (triggeredRecords == null || triggeredRecords.isEmpty()) {
            return false;
        }
        for (TriggeredRecord triggeredRecord : triggeredRecords) {
            if (triggeredRecord.getViewType() == ProfitAndLossAdapter.ITEM_LOSS_NEW
                    || triggeredRecord.getViewType() == ProfitAndLossAdapter.ITEM_PROFIT_NEW) {
                return true;
            }
        }

        return false;
    }

}
